import datetime
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.forms.models import model_to_dict
from django.db.models import ObjectDoesNotExist, F
import json
from MBlog_backend.custom_response import custom_response
import os
import random
import time

# 数据库模型
from article.models import articles as art_model
from user.models import user as user_model
from category.models import category as category_model
from article.models import article_tag as article_tag_model
from tag.models import tag as tag_model


# Create your views here.

def articles(request):
    body = json.loads(request.body)
    query_options, page_size = body.values()
    page_size, page_no, sort_name, sort = page_size.values()
    year, month, category, tags = query_options.values()
    if sort == 'desc':
        sort = '-' + sort_name
    else:
        sort = sort_name

    art_objs = art_model.objects.all().order_by(sort).order_by('-id')
    if category:
        art_objs = art_objs.filter(category__id=category)
    if tags:
        art_objs = art_objs.filter(article_tag__tag_id=tags)
    if all([year, month]):
        art_objs = art_objs.filter(create_time__year=year, create_time__month=month)
    art_objs = art_objs.order_by(sort).values('id', 'artName', 'scan', 'comment_num', 'summary', 'user__nickname',
                                              'create_time')
    paginator = Paginator(art_objs, page_size)
    try:
        page_art_obj = paginator.page(page_no)
    except PageNotAnInteger:
        page_art_obj = paginator.page(1)
    except EmptyPage:
        page_art_obj = paginator.page(paginator.num_pages)
    art_list = []
    for art_dict in page_art_obj:
        art_dict['author'] = art_dict['user__nickname']
        art_dict.pop('user__nickname')
        tag_objs = tag_model.objects.filter(articles=art_dict['id']).values('id', 'tag_name')
        tag_list = []
        if tag_objs:
            tag_list = [x for x in tag_objs]
        art_dict['tags'] = tag_list
        art_list.append(art_dict)
    resp = custom_response()
    resp.data_update(art_list)
    return resp.response


def detail(request):
    pass


def publish(request):
    user_token = request.headers.get('Oauth-Token')
    user_obj = user_model.objects.filter(token__token__exact=user_token).first()
    body = request.body
    body = json.loads(body)
    article = body.get('article')
    id = article.get('id', None)
    artName = article.get('artName')
    art_body = article.get('body')
    content = art_body.get('content')
    content_html = art_body.get('contentHtml')
    summary = article.get('summary')
    # 获取分类id
    category = article.get('category')
    # 获取所有tag名称
    tags = article.get('tags')

    resp = custom_response()
    if id is not None and id != '':
        art_obj = art_model.objects.get(id__exact=id)
        if not art_obj:
            resp.set_code(5001)
            resp.set_message('文章不存在或已被删除！')
            return resp.response
        else:
            art_obj.artName = artName
            art_obj.summary = summary
            art_obj.category_id = category
            art_obj.content = content
            art_obj.user = user_obj
            art_obj.content_html = content_html
            art_obj.save()

    else:
        art_obj = art_model(artName=artName, summary=summary, category_id=category, content=content,
                            user=user_obj, content_html=content_html, )
        art_obj.save()
    if tags:
        art_tag_obj = article_tag_model.objects.filter(article_id=art_obj.id)
        if art_tag_obj:
            art_tag_obj.delete()
        for tag in tags:
            # tag_obj = tag_model.objects.get(id__exact=tag.get('id'))
            art_tag_obj = article_tag_model(article_id=art_obj.id, tag_id=tag.get('id'))
            art_tag_obj.save()
    resp.data_update(articleId=art_obj.id)
    return resp.response


def view(request):
    print(os.path.dirname(__file__))
    body = json.loads(request.body)
    id = body.get('id')
    resp = custom_response()
    art_obj = art_model.objects.get(id__exact=id)
    user_obj = user_model.objects.get(id__exact=art_obj.user.id)
    category_obj = category_model.objects.get(id__exact=art_obj.category_id)
    tags_obj = article_tag_model.objects.filter(article__id=art_obj.id)
    tags = tags_obj.annotate(tagId=F('tag_id'), tagName=F('tag__tag_name')).values('tagId', 'tagName')
    art_dict = {'id': art_obj.id, 'artName': art_obj.artName, 'commentNum': art_obj.comment_num, 'scan': art_obj.scan,
                'summary': art_obj.summary, 'createTime': art_obj.create_time, 'content': art_obj.content,
                'content_html': art_obj.content_html,
                'author': {'userId': user_obj.id, 'nickName': user_obj.nickname, 'avatar': user_obj.avatar},
                'tags': [x for x in tags],
                'category': {'categoryId': category_obj.id, 'categoryName': category_obj.category_name}
                }

    art_obj = art_model.objects.get(id__exact=id)
    art_obj.scan += 1
    art_obj.save()
    resp.data_update(art_dict)
    return resp.response


def hot(request):
    art_objs = art_model.objects.all().values('id', 'artName').order_by('-scan', '-comment_num')[:6]
    art_list = [x for x in art_objs]
    resp = custom_response()
    resp.data_update(art_list)
    return resp.response


def new(request):
    art_objs = art_model.objects.all().values('id', 'artName').order_by('-create_time')[:6]
    art_list = [x for x in art_objs]
    resp = custom_response()
    resp.data_update(art_list)
    return resp.response


def upload(request):
    if request.method == 'POST':
        myFile = request.FILES.get('image')
        resp = custom_response()
        if myFile:
            dir = "/resource"
            destination = open(os.path.join(dir, myFile.name),
                               'wb+')
            for chunk in myFile.chunks():
                destination.write(chunk)
            destination.close()
            suffix = myFile.name.split('.')[-1]
            new_name = str(int(time.time() * 1000)) + '{:06d}'.format(random.randint(0, 999999)) + '.' + suffix
            os.rename(os.path.join(dir, myFile.name), os.path.join(dir, new_name))
            resp.data_update(filename=new_name)
        else:
            resp.set_code("1001")
            resp.set_message("上传失败！")
        return resp.response


def test(request):
    art_model.objects.values('category__id')
